<template>
  <ul class="app-header-nav">
    <li class="home">
      <RouterLink @click="curretIndex = -1" :class="{ active: curretIndex === -1 }" to="/">首页</RouterLink>
    </li>
    <li v-for="(item, index) in list" :key="item.id" @mouseenter="show(item, index)" @mouseleave="hide(item, index)">
      <!-- 一级分类 -->
      <RouterLink :class="{ active: curretIndex === index }" @click="hide(item, index)" :to="`/cate/${item.id}`">{{
        item.name }}
      </RouterLink>
      <!-- 二级分类 -->
      <div class="layer" :class="{ open: item.open }">
        <ul>
          <li v-for="item1 in item.children" :key="item1.id">
            <RouterLink @click="hide(item, index)" :to="`/cate/sub/${item1.id}`">
              <img :src="item1.picture" alt="">
              <p>{{ item1.name }}</p>
            </RouterLink>
          </li>
        </ul>
      </div>
    </li>
  </ul>
</template>
<script setup name="AppHeaderNav">
import { computed, ref } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const list = computed(() => store.state.cate.cateList)
// 定义当前一级分类的索引
const curretIndex = ref(0)

// 控制二级分类的显示和隐藏
function hide(item, index) {
  item.open = false
  // 改变一级分类的激活状态
  curretIndex.value = index
}
function show(item, index) {
  item.open = true
  // 改变一级分类的激活状态
  curretIndex.value = index
}

</script>
<style lang="less" scoped>
.app-header-nav {
  width: 820px;
  display: flex;
  justify-content: space-around;
  padding-left: 40px;
  position: relative;
  z-index: 998;

  >li {
    margin-right: 40px;
    width: 38px;
    text-align: center;

    >a {
      font-size: 16px;
      line-height: 32px;
      height: 32px;
      display: inline-block;

      // 控制一级分类名称的高亮效果
      &.active {
        color: @xtxColor;
        border-bottom: 1px solid @xtxColor;
      }
    }

    &:hover {
      >a {
        color: @xtxColor;
        border-bottom: 1px solid @xtxColor;
      }

      // 鼠标悬浮在一级分类上时，二级分类显示（opacity和height)
      // 为了兼容点击事件和悬浮事件，我们将悬浮时改变样式改为通过数据来控制样式
      /*  >.layer {
        height: 132px;
        opacity: 1;
      } */
    }
  }

  // 二级分类的样式
  .layer {
    width: 1240px;
    background-color: #fff;
    position: absolute;
    left: -200px;
    top: 56px;
    height: 0;
    overflow: hidden;
    opacity: 0;
    box-shadow: 0 0 5px #ccc;
    transition: all .2s .1s;

    // 控制二级分类的显示和隐藏的类
    &.open {
      height: 132px;
      opacity: 1;
    }

    ul {
      display: flex;
      flex-wrap: wrap;
      padding: 0 70px;
      align-items: center;
      height: 132px;

      li {
        width: 110px;
        text-align: center;

        img {
          width: 60px;
          height: 60px;
        }

        p {
          padding-top: 10px;
        }

        &:hover {
          p {
            color: @xtxColor;
          }
        }
      }
    }
  }
}
</style>
